package com.lidroid.xutils.util;

import java.lang.reflect.Method;

/**
 * ReflectUtils
 */
@SuppressWarnings("unchecked")
public class ReflectUtils {

    private ReflectUtils() {
    }

    public static StackTraceElement getCurrentMethodName() {
        StackTraceElement callerTraceElement = null;
        StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
        return stacks[3];
    }

    public static StackTraceElement getCallerMethodName() {
        StackTraceElement callerTraceElement = null;
        StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
        return stacks[4];
    }


    public static Method getMethod(Class clazz, String methodName, Object... args) {
        Method result = null;
        Class[] types = null;
        if (args != null) {
            types = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                types[i] = args[i].getClass();
                if (types[i].equals(Integer.class)) {
                    types[i] = int.class;
                } else if (types[i].equals(Boolean.class)) {
                    types[i] = boolean.class;
                } else if (types[i].equals(Float.class)) {
                    types[i] = float.class;
                } else if (types[i].equals(Double.class)) {
                    types[i] = double.class;
                } else if (types[i].equals(Byte.class)) {
                    types[i] = byte.class;
                } else if (types[i].equals(Character.class)) {
                    types[i] = char.class;
                } else if (types[i].equals(Long.class)) {
                    types[i] = long.class;
                } else if (types[i].equals(Short.class)) {
                    types[i] = short.class;
                }
            }
        }
        try {
            result = clazz.getMethod(methodName, types);
        } catch (NoSuchMethodException e) {
            for (int i = 0; i < args.length; i++) {
                types[i] = args[i].getClass();
            }
            try {
                result = clazz.getMethod(methodName, types);
            } catch (NoSuchMethodException e1) {
            }
        }
        return result;
    }
}
